//
//  MLXIntroduPage.m
//  mlxGuidePage
//
//  Created by SY on 2019/5/4.
//  Copyright © 2019 com.sdzw.duwenquan. All rights reserved.
//

#import "MLXIntroduPage.h"

@interface MLXIntroduPage ()<UIScrollViewDelegate>
{
    NSArray       * _mlxBgViewArr;
    NSInteger       _mlxCenterPageIndex;
    AVPlayer      * _mlxPlayer;
    NSTimer       * _mlxTimer;
    AVPlayerLayer * _mlxPlayerLayer;
}

@end

@implementation MLXIntroduPage

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_mlxPlayer pause];
    _mlxPlayer  = nil;
    [self mlxStopTimer];
    self.view = nil;
}

- (NSArray *)mlxGetPageArr{
    if([self mlxGetPagesNum] <1){
        return  nil;
    }
    if(_mlxPageArr){
        return _mlxPageArr;
    }
    NSMutableArray * tmpArr = [[NSMutableArray alloc]init];
    if(_mlxCoverImgArr){
        [_mlxCoverImgArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [tmpArr addObject:[self mlxGetCoverImgViewWithImgName:obj]];
        }];
    }else if(_mlxCoverTitlesArr){
        [_mlxCoverTitlesArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [tmpArr addObject:[self mlxGetPageWithTitle:obj]];
        }];
    }
    _mlxPageArr = tmpArr;
    return  _mlxPageArr;
}

- (void)mlxReloadCoverTitles{
    for(UILabel * label in _mlxPageArr){
        
        CGFloat height = 30;
        NSString * text = [label.attributedText string];
        if([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending){
            CGSize size = [text sizeWithAttributes:_mlxLabelAttributesDic];
            height = size.height;
        }
        label.attributedText = [[NSAttributedString alloc]initWithString:text attributes:_mlxLabelAttributesDic];
    }
}

- (instancetype)init{
    if(self = [super init]){
        [self mlxInitSelf];
        
    }
    return self;
}

- (void)mlxInitSelf{
    self.mlxAutoScrolling = NO;
    self.mlxAutoLoopPlayVideo = YES;
    [self mlxLayoutEnterBtn];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mlxApplicationWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self mlxStopTimer];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self mlxAddPageScroll];
    [self mlxStartTimer];
    
}

- (void)mlxBringSubViewToFront{
    [self.view bringSubviewToFront:self.mlxPageScrollView];
    [self.view bringSubviewToFront:_mlxPageControl];
    [self.view bringSubviewToFront:self.mlxEnterBtn];
}

- (void)mlxAddVideo{
    if(!_mlxVideoUrl){
        return;
    }
    AVPlayerItem * mlxPlayerItem = [AVPlayerItem playerItemWithURL:_mlxVideoUrl];
    _mlxPlayer = [AVPlayer playerWithPlayerItem:mlxPlayerItem];
    _mlxPlayer.volume = self.mlxVolume;
    
    _mlxPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:_mlxPlayer];
    _mlxPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _mlxPlayerLayer.frame = self.view.layer.bounds;
    [self.view.layer addSublayer:_mlxPlayerLayer];
    
    [_mlxPlayer play];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movidePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:_mlxPlayer.currentItem];
    
    [self mlxBringSubViewToFront];
}

- (void)setMlxVolume:(float)mlxVolume{
    _mlxVolume = mlxVolume;
    _mlxPlayer.volume = mlxVolume;
    
}

- (void)mlxEnter:(id)object{
    [self mlxStopTimer];
    
    if(self.mlxDelegate && [self.mlxDelegate respondsToSelector:@selector(mlxIntroductionViewEnterTap:)]){
        [self.mlxDelegate mlxIntroductionViewEnterTap:object];
    }
    
}

- (void)mlxAddBackgroundViews{
    CGRect frame = self.view.bounds;
    NSMutableArray * tmpArr = [NSMutableArray new];
    [[[_mlxBackgroundImgArr reverseObjectEnumerator] allObjects] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString * suffix;
        if([obj componentsSeparatedByString:@"."]){
            suffix = [obj componentsSeparatedByString:@"."][1];
            
        }
        UIImageView * imgView = [[UIImageView alloc]init];
        if([suffix isEqualToString:@"gif"]){
            NSString * gifImgName = [obj componentsSeparatedByString:@"."][0];
            imgView.image = [UIImage mlx_setAnimatedGIFWithGifName:gifImgName];
        }else {
            imgView.image = [UIImage imageNamed:obj];
            
        }
        
        imgView.frame = frame;
        imgView.tag = idx + 1;
        [tmpArr addObject:imgView];
        [self.view addSubview:imgView];
        
    }];
    _mlxBgViewArr = [[tmpArr reverseObjectEnumerator] allObjects];
    [self.view bringSubviewToFront:self.mlxPageScrollView];
    [self.view bringSubviewToFront:_mlxPageControl];
}

- (void)setMlxBackgroundImgArr:(NSArray *)mlxBackgroundImgArr{
    _mlxBackgroundImgArr = mlxBackgroundImgArr;
    [self mlxAddBackgroundViews];
    
}

- (void)setMlxCoverImgArr:(NSArray *)mlxCoverImgArr{
    _mlxCoverImgArr = mlxCoverImgArr;
    [self mlxReloadPage];
    
}

- (void)setMlxCoverTitlesArr:(NSArray *)mlxCoverTitlesArr{
    _mlxCoverTitlesArr = mlxCoverTitlesArr;
    
    [self mlxReloadPage];
    
}

- (void)setMlxLabelAttributesDic:(NSDictionary *)mlxLabelAttributesDic{
    _mlxLabelAttributesDic = mlxLabelAttributesDic;
    [self mlxReloadCoverTitles];
}

- (void)setMlxVideoUrl:(NSURL *)mlxVideoUrl{
    _mlxVideoUrl = mlxVideoUrl;
    [self mlxAddVideo];
    
}

- (void)mlxAddPageScroll{
    self.mlxPageScrollView = [[UIScrollView alloc]initWithFrame:self.view.bounds];
    self.mlxPageScrollView.delegate = self;
    self.mlxPageScrollView.pagingEnabled = YES;
    self.mlxPageScrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.mlxPageScrollView];
    _mlxPageControl = [[UIPageControl alloc]initWithFrame:[self mlxLayoutPageControlFrame]];
    _mlxPageControl.pageIndicatorTintColor = [UIColor grayColor];
    [self.view addSubview:_mlxPageControl];
    
    
}

- (void)mlxLayoutEnterBtn{
    if(!self.mlxEnterBtn){
        self.mlxEnterBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.mlxEnterBtn setTitle:@"进入" forState:UIControlStateNormal];
        self.mlxEnterBtn.layer.borderWidth = 0.5;
        self.mlxEnterBtn.layer.borderColor = [UIColor whiteColor].CGColor;
        self.mlxEnterBtn.hidden = NO;
        self.mlxEnterBtn.frame = [self mlxLayoutEnterBtnFrame];
    }
    [self.mlxEnterBtn addTarget:self action:@selector(mlxEnter:) forControlEvents:UIControlEventTouchUpInside];
    self.mlxEnterBtn.alpha = 0;
}

- (CGRect)mlxLayoutPageControlFrame{
    CGRect mlxFrame = CGRectMake(0, self.view.bounds.size.height - 50, self.view.bounds.size.width, 30);
    return CGRectOffset(mlxFrame,self.mlxPageControlOffSet.x, self.mlxPageControlOffSet.y);
}

- (CGRect)mlxLayoutEnterBtnFrame{
    CGSize size = self.mlxEnterBtn.bounds.size;
    if(CGSizeEqualToSize(size, CGSizeZero)){
        size = CGSizeMake(self.view.frame.size.width * 0.6, 40);
    }
    return CGRectMake(self.view.frame.size.width/2 -size.width/2,_mlxPageControl.frame.origin.y - size.height/2, size.width, size.height);
}

- (void)mlxStartTimer{
    if(_mlxAutoScrolling){
        _mlxTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(mlxOnTimer) userInfo:nil repeats:YES];
    }
}

- (void)mlxOnTimer{
    CGRect frame = self.mlxPageScrollView.frame;
    frame.origin.x = frame.size.width * (_mlxPageControl.currentPage + 1);
    frame.origin.y = 0;
    if(frame.origin.x >= self.mlxPageScrollView.contentSize.width){
        frame.origin.x = 0;
    }
    [self.mlxPageScrollView scrollRectToVisible:frame animated:YES];
}

- (void)mlxStopTimer{
    [_mlxTimer invalidate];
    _mlxTimer = nil;
}

- (void)mlxReloadPage{
    _mlxPageControl.numberOfPages = [self mlxGetPagesNum];
    _mlxPageScrollView.contentSize = [self mlxGetScrollContentSize];
    __block CGFloat x = 0;
    NSArray * mlxPageArr = [self mlxGetPageArr];
    [mlxPageArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIView * view = (UIView *)obj;
        view.frame = CGRectOffset(view.frame, x, 0);
        [self.mlxPageScrollView addSubview:view];
        x += view.frame.size.width;
        if(idx == mlxPageArr.count - 1){
            [view addSubview:self.mlxEnterBtn];
        }
        
    }];
    
    if(_mlxPageControl.numberOfPages == 1){
        _mlxEnterBtn.alpha = 1;
        _mlxPageControl.alpha = 0;
    }
    if(self.mlxPageScrollView.contentSize.width == self.mlxPageScrollView.frame.size.width){
        self.mlxPageScrollView.contentSize = CGSizeMake(self.mlxPageScrollView.contentSize.width + 1, self.mlxPageScrollView.contentSize.height);
    }
    
}

- (void)setMlxAutoScrolling:(BOOL)mlxAutoScrolling{
    _mlxAutoScrolling = mlxAutoScrolling;
    if(!_mlxTimer&&_mlxAutoScrolling){
        [self mlxStartTimer];
    }
}

- (NSInteger)mlxGetPagesNum{
    if(_mlxCoverImgArr){
        return _mlxCoverImgArr.count;
        
    }else if(_mlxCoverTitlesArr){
        return _mlxCoverTitlesArr.count;
        
    }
    return 0;
}

- (NSInteger)mlxGetCurrentPage{
    return self.mlxPageScrollView.contentOffset.x/self.view.bounds.size.width;
}

- (CGSize)mlxGetScrollContentSize{
    UIView * view = [[self mlxGetPageArr] firstObject];
    return CGSizeMake(view.frame.size.width* _mlxPageArr.count, view.frame.size.height);
}

- (void)mlxApplicationWillEnterForeground:(id)sender{
    [_mlxPlayer play];
}

- (void)mlxPageControlChangePage:(UIScrollView *)pageScrollView{
    
    if([self mlxIsLastPage:_mlxPageControl]){
        if(_mlxPageControl.alpha == 1){
            [UIView animateWithDuration:1 animations:^{
                _mlxEnterBtn.alpha = 1;
                _mlxPageControl.alpha = 0;
            }];
        }
    }else{
        if(_mlxPageControl.alpha == 0){
            [UIView animateWithDuration:1 animations:^{
                _mlxEnterBtn.alpha = 0;
                _mlxPageControl.alpha = 1;
            }];
        }
    }
}

- (BOOL)mlxIsLastPage:(UIPageControl *)pageControl{
    return pageControl.numberOfPages == pageControl.currentPage + 1;
}

- (BOOL)mlxIsGoOnNext:(UIPageControl *)pageControl{
    return pageControl.numberOfPages>pageControl.currentPage + 1;
}

- (UIView *)mlxGetPageWithTitle:(NSString *)title{
    CGSize size = self.view.frame.size;
    CGRect rect;
    CGFloat height = 30;
    if([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending){
        CGSize size = [title sizeWithAttributes:_mlxLabelAttributesDic];
        height = size.height;
    }
    rect = CGRectMake(0, size.height - height - 100, size.width, height);
    UILabel * label = [[UILabel alloc]initWithFrame:rect];
    label.textAlignment = NSTextAlignmentCenter;
    label.attributedText = [[NSAttributedString alloc]initWithString:title attributes:_mlxLabelAttributesDic];
    return  label;
}

- (UIView *)mlxGetCoverImgViewWithImgName:(NSString *)imgName{
    
    UIImageView * imgView = [[UIImageView alloc]init];
    if([imgName componentsSeparatedByString:@"."].count>1&&[[imgName componentsSeparatedByString:@"."][1] isEqualToString:@"gif"]){
        
        NSString * gifImgName = [imgName componentsSeparatedByString:@"."][0];
        imgView.image = [UIImage mlx_setAnimatedGIFWithGifName:gifImgName];
    }else{
        imgView.image = [UIImage imageNamed:imgName];
    }
    imgView.contentMode = UIViewContentModeScaleAspectFill;
    imgView.clipsToBounds = YES;
    imgView.userInteractionEnabled = YES;
    CGSize size = self.view.bounds.size;
    
    imgView.frame = CGRectMake(0,0, size.width, size.height);
    return imgView;
}

- (void)mlxApplicationWillEnterForground:(id)sender{
    [_mlxPlayer play];
}

#pragma mark-mlx ---------------------通知事件位置---------------------------------
- (void)movidePlayDidEnd:(NSNotification *)notification{
    if(_mlxAutoLoopPlayVideo){
        AVPlayerItem * item = [notification object];
        [item seekToTime:kCMTimeZero];
        [_mlxPlayer play];
    }else{
        [self mlxEnter:nil];
    }
}

#pragma mark-mlx -------------------代理位置-------------------------------------------
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSInteger index = scrollView.contentOffset.x/self.view.frame.size.width;
    CGFloat mlxAlpha =  1-(scrollView.contentOffset.x - index*self.view.bounds.size.width)/self.view.bounds.size.width;
    if([_mlxBgViewArr count] >index){
        UIView * view = [_mlxBgViewArr objectAtIndex:index];
        if(view){
            view.alpha = mlxAlpha;
        }
    }
    [_mlxPageControl setCurrentPage:[self mlxGetCurrentPage]];
    [self mlxPageControlChangePage:scrollView];
    if(scrollView.isTracking){
        [self mlxStopTimer];
    }else{
        if(!_mlxTimer){
            [self mlxStartTimer];
        }
    }
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    if([scrollView.panGestureRecognizer translationInView:scrollView.superview].x<0){
        if(![self mlxIsGoOnNext:_mlxPageControl]){
            [self mlxEnter:nil];
        }
    }
}
@end
